package com.framework.network.factory

import com.framework.network.factory.converter.LenientGsonRequestBodyConverter
import com.framework.network.factory.converter.LenientGsonResponseBodyConverter
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type

/**
 * 将服务器的数据统一转换处理
 */
class LenientGsonConverterFactory(gson: Gson?) : Converter.Factory() {
    private val gson: Gson

    init {
        if (gson == null) throw NullPointerException("gson == null")
        this.gson = gson
    }

    companion object {
        @JvmOverloads
        fun create(gson: Gson? = Gson()): LenientGsonConverterFactory {
            return LenientGsonConverterFactory(gson)
        }
    }

    override fun responseBodyConverter(
        type: Type, annotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return LenientGsonResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<Annotation>,
        methodAnnotations: Array<Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody> {
        val adapter = gson.getAdapter(TypeToken.get(type))
        return LenientGsonRequestBodyConverter(gson, adapter)
    }


}